package handler

import (
	"hotel_Manager_Api/model/dbModel"
	"github.com/martini-contrib/encoder"
	"hotel_Manager_Api/model/dbEngin"
	"hotel_Manager_Api/util"
	"hotel_Manager_Api/model/dto"
	"fmt"
	"github.com/go-martini/martini"
	"strconv"
	"hotel_Manager_Api/handler/wechat"
)

func GetAllDesks(enc encoder.Encoder,page dto.PageCondition)(int,[]byte)  {
	db := dbEngin.GetEnging()
	desk := new(dbModel.Desk)
	deskCount,err := db.Count(desk)

	if err==nil{
		desks := make([]dbModel.Desk,0)
		db.Limit(page.GetPageSizeAndOffset()).Find(&desks)
		pageResult := page.GetPageResult(int(deskCount),desks)
		return 200, encoder.Must(enc.Encode(pageResult));
	}
	return 500,encoder.Must(enc.Encode(err))
}

func NewDesk(desk dbModel.Desk,idGenerate util.IdGenerator,enc encoder.Encoder)(int,[] byte) {
	db:=dbEngin.GetEnging()
	desk.Id = idGenerate.GenerateNewId();
	qrCode,err := wechat.GetWeixin().CreateQRLimitSceneByString(fmt.Sprintf("%d", desk.Id)  )
	if(err != nil){
		return 500,nil
	}
	desk.QrcodeContent = qrCode.Url
	desk.QrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+qrCode.Ticket
	_,err = db.Insert(desk)
	if err == nil{
		return 201, encoder.Must(enc.Encode(desk))
	}else {
		errResponse := util.StandardResult{Message:fmt.Sprint(err)}
		return 500,encoder.Must(enc.Encode(errResponse))
	}
}

func EditDesk(params martini.Params,desk dbModel.Desk, enc encoder.Encoder) (int, []byte) {
	db := dbEngin.GetEnging()
	desk.Id,_ = strconv.ParseInt(params["id"],10,64) ;
	_,err := db.ID(desk.Id).Update(desk)
	if err== nil{
		return 200,encoder.Must(enc.Encode(desk))
	}else {
		fmt.Println(err)
		return 500,encoder.Must(enc.Encode(err))
	}
}

func DeleteDesk(params martini.Params) (int,[]byte)  {
	id,_ := strconv.ParseInt(params["id"],10,64) ;
	db := dbEngin.GetEnging()
	desk := new(dbModel.Desk)
	db.Id(id).Delete(desk)

	return 204,make([]byte,0)
}
